import React, { createContext, FC, useEffect, useContext, createElement } from 'react';
import { createFormContainerProcessor } from './FormContainerProcessor';
import { useCreation } from 'ahooks';
import { getSelectorData } from '../../fields/checkbox-group/utils';

export function generateSelector<R extends any, S extends any>(
  Context: React.Context<any>,
  selector: (s: S) => R,
) {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const tableState = useContext(Context);
  let currState = selector(tableState);

  currState = getSelectorData(currState);
  return currState;
}

// 去除Observable类型
export type FormContainerProcessorWipe = any;
export interface IFormContainerProviderProps {
  children: React.ReactElement;
  // 是否是H5
  isMobile: boolean;
}

const Context = createContext({} as any);

export const FormContainerProvider: FC<IFormContainerProviderProps> = ({ children, isMobile }) => {
  const processorAction = useCreation(() => {
    return createFormContainerProcessor();
  }, []);
  const { processor, getRoot, destroy } = processorAction || {};

  useEffect(() => {
    processor.setMobile(isMobile);
  }, [isMobile]);

  useEffect(() => {
    return () => {
      destroy?.();
    };
  }, []);

  return <Context.Provider value={processor!}>{children}</Context.Provider>;
};

/**
 * selector选择器
 * @param selector
 * @returns
 */
export function useFormContainerSelector<R extends any>(
  selector: (s: FormContainerProcessorWipe) => R,
) {
  return generateSelector<R, FormContainerProcessorWipe>(Context, selector);
}
